#include "network/datagram_socket.h"

#include "network/datagram_packet.h"
#include "network/socket_address.h"

namespace network {

DatagramSocket::DatagramSocket() {
    socket_ = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
}

DatagramSocket::~DatagramSocket() {
    closesocket(socket_);
}

void DatagramSocket::Bind(const SocketAddress& address) {
    // TODO(patrick): Error checking.

    // Allow broadcast messages.
    SetOption(SOL_SOCKET, SO_BROADCAST, 1);

    // Allow for port reuse.
    SetOption(SOL_SOCKET, SO_REUSEADDR, 1);

    // Set non-blocking.
    unsigned long non_blocking = 1;
    ioctlsocket(socket_, FIONBIO, &non_blocking);

    const sockaddr_in& socket_address = address.GetSocketAddress();
    bind(socket_, reinterpret_cast<const SOCKADDR*>(&socket_address), sizeof(socket_address));
}

void DatagramSocket::Send(const SocketAddress& address, const DatagramPacket& packet) {
}

void DatagramSocket::Receive(const SocketAddress& address, DatagramPacket& packet) {
}

int DatagramSocket::SetOption(int level, int name, unsigned long value) {
    return setsockopt(socket_, level, name, reinterpret_cast<char*>(&value), sizeof(value));
}

} // namespace network
